﻿using System;
using System.IO;
using System.Reflection;

namespace FlickrXplorer.Web.Plugin
{
  /// <summary>
  /// Represents a part of the page that holds content.
  /// </summary>                                       
  public class ContentSection
  {
    private const string contentReplaceKeyword = "{content}";

    public string Content { get; set; }
    internal string Template { get; set; }

    /// <summary>
    /// Creates a new <see cref="FlickrXplorer.Web.Plugin.ContentSection" text="ContentSection" />
    /// with no wrapper template.
    /// </summary>                                                                                
    internal ContentSection()
      : this(null)
    {
    }

    /// <summary>
    /// Creates a new <see cref="FlickrXplorer.Web.Plugin.ContentSection" text="ContentSection" />
    /// with a template.
    /// </summary>
    /// <remarks>
    /// The <see cref="FlickrXplorer.Web.Plugin.ContentSection.Template" text="Template" />
    /// must contain the string <b>{content} </b>and will be replaced
    /// with the plugin's content when it is rendered.
    /// </remarks>
    /// <param name="template">The template to be used for this
    ///                        ContentSection.</param>                                            
    internal ContentSection(string template) : this(template, TemplateType.RawString)
    {
    }

    internal ContentSection(string template, TemplateType templateType)
    {
      if (templateType == TemplateType.EmbeddedResourceFile)
      {
        this.Template = LoadTemplateFromEmbeddedResource(template);
      }
      else
      {
        this.Template = template;
      }
    }

    private string LoadTemplateFromEmbeddedResource(string location)
    {
      using (StreamReader sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(location)))
      {
        string template = sr.ReadToEnd();
        return template;
      }
    }

    /// <summary>
    /// \Returns the rendered content of this <see cref="FlickrXplorer.Web.Plugin.ContentSection" text="ContentSection" />.
    /// </summary>
    /// <returns>
    /// The rendered content.
    /// </returns>
    /// <remarks>
    /// At this point the content and the template are merged and
    /// returned to the caller.
    /// </remarks>                                                                                                         
    public override string ToString()
    {
      if (String.IsNullOrEmpty(this.Template))
      {
        return Content;
      }
      else
      {
        return Template.Replace(contentReplaceKeyword, Content);
      }
    }
  }
}
